package com.example.autopia.view.Activities

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.util.Patterns
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.autopia.databinding.ActivityCreateAccBinding
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.utilities.PreferenceManager
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthException
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase


class CreateAccActivity : AppCompatActivity() {
    private lateinit var binding: ActivityCreateAccBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCreateAccBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.bLogin.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
            finish()
        }

        binding.ibCreateAcc.setOnClickListener {
            createAccount()
        }
    }

    private fun createAccount() {
        val email = binding.etEmail.text.toString()
        val password = binding.etPassword.text.toString()

        val isValidated: Boolean = validateData(email, password)
        if (isValidated) {
            createAccountInFirebase(email, password)
        }
    }

    private fun createAccountInFirebase(email: String, password: String) {
        changeProgress(true)
        val firebaseAuth = Firebase.auth
        firebaseAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this) { task ->
                changeProgress(false)
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Toast.makeText(
                        this@CreateAccActivity,
                        "Аккаунт создан, зайдите на вашу почту",
                        Toast.LENGTH_SHORT
                    ).show()
                    firebaseAuth.currentUser?.sendEmailVerification()
                    // generate userName
                    val userName = if (binding.etName.text.isNullOrEmpty()) {
                        "User${firebaseAuth.currentUser!!.uid.slice(2..7)}"
                    } else {
                        binding.etName.text
                    }
                    // Add user to realtime database
                    UsersRepository().addUser(
                        firebaseAuth.currentUser?.uid ?: "",
                        email,
                        userName.toString(),
                        password
                    )
                    // добавление имя и почту пользователя в shared preference
                    val userPreference: PreferenceManager = PreferenceManager(this@CreateAccActivity)
                    userPreference.putString("userName", userName.toString())
                    userPreference.putString("userEmail", email)
                    userPreference.putString("userBalance", "0")

                    FirebaseAuth.getInstance().signOut()
                    val intent = Intent(this, LoginActivity::class.java)
                    startActivity(intent)
                    finish()
                } else {
                    // If sign in fails, display a message to the user
                    Log.d("frikadelka", task.exception.toString())
                    Log.d("frikadelka", task.exception?.localizedMessage.toString())
                    if (task.exception?.localizedMessage?.contains("The email address is already in use by another account") == true) {
                        Toast.makeText(
                            this@CreateAccActivity,
                            "На данную почту уже создан аккаунт",
                            Toast.LENGTH_SHORT
                        ).show()
                    } else if (task.exception?.localizedMessage?.contains("A network error") == true){
                        Toast.makeText(
                            this@CreateAccActivity,
                            "Нет соединения с Интернетом",
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        Toast.makeText(
                            this@CreateAccActivity,
                            task.exception?.localizedMessage ?: "error",
                            Toast.LENGTH_SHORT
                        ).show()
                    }


                }
            }
    }

    private fun validateData(email: String, password: String): Boolean {
        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            binding.etEmail.error = "Некорректный формат почты"
            return false
        }
        if (password.length < 6) {
            binding.etPassword.error = "Пароль должен быть больше 5 символов"
            return false
        }
        return true
    }

    private fun changeProgress(inProgress: Boolean) {
        if (inProgress) {
            binding.loading.visibility = View.VISIBLE
            binding.cvCreateAcc.visibility = View.GONE
        } else {
            binding.loading.visibility = View.GONE
            binding.cvCreateAcc.visibility = View.VISIBLE
        }
    }
}